{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1739b794",
   "metadata": {},
   "outputs": [],
   "source": [
    "from selenium import webdriver\n",
    "import requests\n",
    "from time import sleep\n",
    "import datetime\n",
    "import json\n",
    "import pandas as pd\n",
    "import os\n",
    "import random\n",
    "import sys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "12e80b78",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 通过selenium登陆获取cookie\n",
    "def get_cookie(user_):\n",
    "    \n",
    "    url_ = 'https://swufeapp.iswufe.info/jinzhi/index.php'\n",
    "    \n",
    "    chrome_options = webdriver.ChromeOptions()\n",
    "    chrome_options.add_argument('--headless')  # # 浏览器不提供可视化页面\n",
    "\n",
    "    # 拿到cookie\n",
    "    # cookie有效期半小时左右\n",
    "    driver = webdriver.Chrome(options=chrome_options)\n",
    "    driver.get(url_)\n",
    "    driver.find_element_by_xpath('//*[@id=\"username\"]').send_keys(user_['name'])\n",
    "    driver.find_element_by_xpath('//*[@id=\"password\"]').send_keys(user_['password'])\n",
    "    driver.find_element_by_xpath('//*[@id=\"casLoginForm\"]/p[4]/button').click()\n",
    "    sleep(2)\n",
    "    \n",
    "    # 打卡cookie\n",
    "    # cookie_ = driver.get_cookies()[0]\n",
    "    \n",
    "    # 报备cookie\n",
    "    driver.get('https://qxj.iswufe.info/QJ/XSBBList')\n",
    "    sleep(1)\n",
    "    cookie_ = driver.get_cookies()\n",
    "    cookie_0 = cookie_[0]['name'] + '=' + cookie_[0]['value']\n",
    "    cookie_1 = cookie_[1]['name'] + '=' + cookie_[1]['value']\n",
    "    \n",
    "    driver.quit()\n",
    "    # return cookie_['name']+'='+cookie_['value']\n",
    "    return cookie_0 + ';' + cookie_1\n",
    "\n",
    "# 个人信息用于提交报备表单\n",
    "def get_profile(cookie_):\n",
    "    \n",
    "    url_ = 'https://qxj.iswufe.info/QJ/GetStuBBList'\n",
    "    \n",
    "    # 拿到个人基本信息,第一次时运行\n",
    "    headers = {\n",
    "        'cookie': cookie_,\n",
    "        'Host': 'qxj.iswufe.info',\n",
    "        'Origin': 'https://qxj.iswufe.info',\n",
    "        'Referer': 'https://qxj.iswufe.info/QJ/XSBBList',\n",
    "        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'\n",
    "    }\n",
    "    \n",
    "    # 请求获取个人信息\n",
    "    limit_time = 5\n",
    "\n",
    "    while limit_time > 0:\n",
    "        try:\n",
    "            response = requests.post(url_, headers=headers, timeout=5)\n",
    "            break\n",
    "        except requests.exceptions.Timeout:\n",
    "            print('获取个人信息请求超时')\n",
    "            limit_time -= 1\n",
    "            \n",
    "    t = response.text\n",
    "    \n",
    "    profile = json.loads(json.loads(t))[-1]\n",
    "    print(profile)\n",
    "    xh = profile['XH']\n",
    "    xm = profile['XM']\n",
    "    lxfs = profile['LXFS']\n",
    "    xy = profile['XY']\n",
    "    fdyid = profile['COUN_EMPLID']\n",
    "    \n",
    "    profile_dict = {\n",
    "        'xh': xh,\n",
    "        'xm': xm,\n",
    "        'xy': xy,\n",
    "        'lxfs': lxfs,\n",
    "        'fdyid': fdyid\n",
    "    }\n",
    "    \n",
    "    return profile_dict\n",
    "\n",
    "\n",
    "def get_latest_info_baobei(cookie_):\n",
    "    \n",
    "    url_ = 'https://qxj.iswufe.info/QJ/GetStuBBList'\n",
    "    \n",
    "    # 拿到个人基本信息,第一次时运行\n",
    "    headers = {\n",
    "        'cookie': cookie_,\n",
    "        'Host': 'qxj.iswufe.info',\n",
    "        'Origin': 'https://qxj.iswufe.info',\n",
    "        'Referer': 'https://qxj.iswufe.info/QJ/XSBBList',\n",
    "        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'\n",
    "    }\n",
    "    \n",
    "    # 请求获取个人信息\n",
    "    response = requests.post(url_, headers=headers)\n",
    "    t = response.text\n",
    "    \n",
    "    profile = json.loads(json.loads(t))[-1]\n",
    "    xh = profile['XH']\n",
    "    baobei_status = profile['STATUS']\n",
    "    out_time = profile['QJKSSJ']\n",
    "    back_time = profile['QJJSSJ']\n",
    "    isvalid = profile['ISVALID']\n",
    "    \n",
    "    if isvalid == '0':\n",
    "        isvalid = '待出行'\n",
    "    else:\n",
    "        isvalid = '已失效'\n",
    "        \n",
    "    profile_dict = {\n",
    "        'xh': xh,\n",
    "        'isvalid': isvalid,\n",
    "        'out_time': out_time,\n",
    "        'back_time': back_time\n",
    "    }\n",
    "    \n",
    "    return profile_dict\n",
    "\n",
    "\n",
    "def fix_variable(x_0, x_1, x_2):\n",
    "    m = {\n",
    "        'qjyy': x_0,\n",
    "        'mdd': x_1,\n",
    "        'qjxc': x_2\n",
    "    }\n",
    "    return m\n",
    "\n",
    "# 提交报备表单\n",
    "def post_bb(cookie_, data):\n",
    "    \n",
    "    url_ = 'https://qxj.iswufe.info/QJ/InsertStuBB'\n",
    "    headers = {\n",
    "        'cookie': cookie_,\n",
    "        'Host': 'qxj.iswufe.info',\n",
    "        'Origin': 'https://qxj.iswufe.info',\n",
    "        'Referer': 'https://qxj.iswufe.info/QJ/XSBBList',\n",
    "        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'\n",
    "    }\n",
    "\n",
    "    # 请求报备\n",
    "    limit_time = 5\n",
    "\n",
    "    while limit_time > 0:\n",
    "        try:\n",
    "            response = requests.post(url_, headers=headers, data=data, timeout=5)\n",
    "            break\n",
    "        except requests.exceptions.Timeout:\n",
    "            print('报备请求超时')\n",
    "            limit_time -= 1\n",
    "\n",
    "    return response.status_code\n",
    "    \n",
    "def save_log(log_):\n",
    "    with open('{}_{}.txt'.format(log_['学号'], log_['timestamp']), 'w', encoding='gbk') as file:\n",
    "        file.write(json.dumps(log_, ensure_ascii=False))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69f10054",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 日志\n",
    "log = {\n",
    "    '学号': '',\n",
    "    '获取cookie': '',\n",
    "    '获取个人信息': '',\n",
    "    '读取个人信息': '',\n",
    "    '报备理由组合': '',\n",
    "    '报备结果': '',\n",
    "    'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H-%M'),\n",
    "    'time_cost': ''\n",
    "}\n",
    "start_time = datetime.datetime.now()\n",
    "\n",
    "## 初始化账号、密码\n",
    "# 输入学号和密码, str\n",
    "user = {'name': '', 'password': ''}\n",
    "\n",
    "# user_type决定报备理由组合\n",
    "user_type = '5'\n",
    "\n",
    "# 日志——学号\n",
    "log['学号'] = user['name']\n",
    "\n",
    "# 尝试两次\n",
    "retry_time = 2\n",
    "\n",
    "while retry_time > 0:\n",
    "    # 获取临时cookie\n",
    "    try:\n",
    "        print('正在登陆……')\n",
    "        cookie_ = get_cookie(user)\n",
    "        if cookie_[:3] == 'org':\n",
    "            log['获取cookie'] = '失败_密码有误' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "            save_log(log)\n",
    "            sys.exit(0)\n",
    "        log['获取cookie'] = '成功_' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "        break\n",
    "    except:\n",
    "        log['获取cookie'] = '失败_' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "        save_log(log)\n",
    "        retry_time -= 1\n",
    "        if retry_time == 0:\n",
    "            sys.exit(0)\n",
    "        \n",
    "\n",
    "## 检查是否第一次登陆\n",
    "# 如果不是第一次登陆，跳过\n",
    "# 如果是第一次登陆，获得个人基本信息并保存成csv\n",
    "try:\n",
    "    if '{}.xlsx'.format(user['name']) in os.listdir():\n",
    "        log['获取个人信息'] = '成功_已存在_' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "        pass\n",
    "    else:\n",
    "        profile_ = get_profile(cookie_)\n",
    "        pd.DataFrame(profile_, index=[0]).to_excel('{}.xlsx'.format(user['name']), index=False, encoding='gbk')\n",
    "        log['获取个人信息'] = '成功_新获取_' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "except:\n",
    "    log['获取个人信息'] = '失败_' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "    save_log(log)\n",
    "    sys.exit(0)\n",
    "    \n",
    "# 读取个人信息\n",
    "try:\n",
    "    df_profile = pd.read_excel('{}.xlsx'.format(user['name']), dtype=object)\n",
    "    log['读取个人信息'] = '成功_' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "except:\n",
    "    log['获取个人信息'] = '失败_' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "    save_log(log)\n",
    "    sys.exit(0)\n",
    "\n",
    "## 报备理由组合\n",
    "## 可变选项\n",
    "variable_dict = {\n",
    "    'qjyy': ['购买生活物资', '拿快递', '吃饭', '理发', '找导师'],\n",
    "    'mdd': ['南门', '北二门', '文化宫', '柳林'],\n",
    "    'qjxc': ['步行', '地铁', '公交', '打车']\n",
    "}\n",
    "\n",
    "## 固定选项\n",
    "# 进出时间\n",
    "now_time = datetime.datetime.now() - datetime.timedelta(minutes=5)\n",
    "back_time = (now_time + datetime.timedelta(hours=2)).strftime('%H:%M')\n",
    "now_time = now_time.strftime('%H:%M')\n",
    "fixed_dict = {\n",
    "    'qjlx': '5',\n",
    "    'szxq': '光华校区',\n",
    "    'upTemp': '',\n",
    "    'qjkssj': now_time,\n",
    "    'qjjssj': back_time,\n",
    "}\n",
    "\n",
    "# 加上个人信息\n",
    "profile_.update(fixed_dict)\n",
    "\n",
    "# 随机获得可变组合\n",
    "if user_type == '0':\n",
    "    variable_d = fix_variable('购买生活物资', '南门', '步行')\n",
    "elif user_type == '1':\n",
    "    variable_d = fix_variable('拿快递', '北二门', '步行')\n",
    "elif user_type == '2':\n",
    "    variable_d = fix_variable('找导师', '柳林', '地铁')\n",
    "else:\n",
    "    variable_d = {}\n",
    "    for x in variable_dict.keys():\n",
    "        variable_d.update({x:random.sample(variable_dict[x], 1)[0]})\n",
    "\n",
    "# 获得最终上传表单\n",
    "profile_.update(variable_d)\n",
    "log['报备理由组合'] = profile_\n",
    "\n",
    "# 报备\n",
    "try:\n",
    "    bb_status = post_bb(cookie_, profile_)\n",
    "    if bb_status == 200:\n",
    "        log['报备结果'] = '成功_' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "        log['time_cost'] = str((datetime.datetime.now() - start_time).seconds)\n",
    "        print('报备成功')\n",
    "        save_log(log)\n",
    "    else:\n",
    "        log['报备结果'] = '失败_' + str(bb_status) + '_' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "        save_log(log)\n",
    "except:\n",
    "    log['报备结果'] = '失败_报错' + datetime.datetime.now().strftime('%H:%M:%S')\n",
    "    save_log(log)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "cookie",
   "language": "python",
   "name": "cookie"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
